package cn.usbtg.common.idmanager;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * id生成管理器
 */
public class BtgIdManager implements IdManager {
    private IdGenerater defaultIdGenerater;
    private static Map<String, IdGenerater> generaters = new ConcurrentHashMap<String, IdGenerater>();//id生成器容器
    private static final BtgIdManager me = new BtgIdManager(); //单例

    public static BtgIdManager me() {
        return me;
    }

    @Override
    public IdGenerater createGenerater(String name) {
        IdGenerater generater = new BtgIdGenerater(name);
        generaters.put(name, generater);
        if (defaultIdGenerater == null) {
            synchronized (BtgIdManager.class) {
                if (defaultIdGenerater == null) {
                    defaultIdGenerater = generater;
                }
            }
        }
        return generater;
    }

    @Override
    public IdGenerater use(String name) {
        IdGenerater idGenerater = generaters.get(name);
        if (idGenerater == null) {
            throw new IllegalStateException("id generater does not exist, name:" + name);
        }
        return generaters.get(name);
    }

    @Override
    public String last() {
        if (defaultIdGenerater == null) {
            throw new IllegalStateException("default id generater does not exist");
        }
        return defaultIdGenerater.last();
    }

    @Override
    public String next(Object... params) {
        if (defaultIdGenerater == null) {
            throw new IllegalStateException("default id generater does not exist");
        }
        return defaultIdGenerater.next(params);
    }
}